import { Observable } from 'rxjs';

export function requestImgs(srcArr, succCallback, failCallback) {
  let total = srcArr.length;
  if (total === 0) {
    throw new Error('不能传入空的数据');
  }
  let loaded = 0;
  const tasks = srcArr.map((url) => {
    return new Promise((resolve) => {
      const img = new Image();
      img.src = url;
      img.onload = () => {
        resolve({
          url,
          img,
          status: 'success',
        });
        loaded++;
        succCallback && succCallback({ loaded, total, url });
      };
      img.onerror = (err) => {
        resolve({
          url,
          status: 'failed',
          err,
        });
        failCallback && failCallback({ url, err });
      };
    });
  });
  return Promise.all(tasks);
}

export function request(url) {
  return new Observable((observer) => {
    setTimeout(() => {
      observer.next(url + ' respone');
      observer.complete();
    }, 1000);
  });
}

export function badRequest(url) {
  return new Observable((observer) => {
    setTimeout(() => {
      observer.error(url + ' 500 Server');
      observer.complete();
    }, 1000);
  });
}
